package com.example.beat_x3.Fragments;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.beat_x3.Adapter.BorrowAdapter;
import com.example.beat_x3.Adapter.LendAdapter;

import com.example.beat_x3.Client.GetResult;
import com.example.beat_x3.Client.HandleChats;

import com.example.beat_x3.R;

import Entity.Inf;
import Entity.Rentals;

public class RentalFragment extends MyFragment {
    public BorrowAdapter borrowAdapter;
    public LendAdapter lendAdapter;
    boolean isRefresh=false;
    private final Handler myHandler = new Handler(Looper.getMainLooper()) {
        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                borrowAdapter.notifyDataSetChanged();
            } else if(msg.what==1){
                lendAdapter.notifyDataSetChanged();
            }
            else {
                lendAdapter.notifyItemChanged((int)msg.obj);
                Toast.makeText(Inf.context, "成功", Toast.LENGTH_SHORT).show();
            }
        }
    };

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.fragment_rental, null);
        RecyclerView recyclerView = view.findViewById(R.id.rental_re);
        recyclerView.setLayoutManager(new LinearLayoutManager(Inf.context));
        borrowAdapter = new BorrowAdapter();
        borrowAdapter.setOnItemClickListener(new BorrowAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String opposite) {
                AlertDialog.Builder builder = new AlertDialog.Builder(Inf.context);
                View viewInflated = LayoutInflater.from(Inf.context).inflate(R.layout.dialogue_reservation, null, false);
                EditText input = viewInflated.findViewById(R.id.input);
                input.setHint(R.string.hint_contact);
                builder.setTitle(R.string.app_name);
                builder.setMessage("联系对方");
                builder.setView(viewInflated);
                builder.setPositiveButton("发送", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (input.length() != 0) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    HandleChats.uploadChat(opposite, Inf.stuInf.StudentAccount, input.getText().toString());
                                    Looper.prepare();
                                    Toast.makeText(Inf.context, "发送成功", Toast.LENGTH_SHORT).show();
                                    Looper.loop();
                                }
                            }).start();
                        }
                    }
                });
                builder.setNegativeButton("取消", null);
                AlertDialog alert = builder.create();
                alert.show();
            }
        });
        lendAdapter = new LendAdapter();

        lendAdapter.setOnItemClickListener(new LendAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String rentalNumber, String equipmentNumber, String studentBorrow, String deadline, int position) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(Inf.context);
                dialog.setTitle("是否归还:");
                dialog.setPositiveButton("确认归还", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if(GetResult.ReturnInstrumentGR(rentalNumber,equipmentNumber,studentBorrow,deadline,1)==1){
                                    lendAdapter.lends.get(position).RentalStatus=1;
                                    isRefresh=true;
                                    Message message=new Message();
                                    message.what=2;
                                    message.obj=position;
                                    myHandler.sendMessage(message);
                                }
                            }
                        }).start();
                    }
                });
                dialog.setNegativeButton("丢失", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if(GetResult.ReturnInstrumentGR(rentalNumber,equipmentNumber,studentBorrow,deadline,3)==1){
                                    lendAdapter.lends.get(position).RentalStatus=2;
                                    isRefresh=true;
                                    Message message=new Message();
                                    message.what=2;
                                    message.obj=position;
                                    myHandler.sendMessage(message);
                                }
                            }
                        }).start();
                    }
                });
                dialog.show();
            }
        });
        recyclerView.setAdapter(lendAdapter);
        recyclerView.setLayoutManager(new GridLayoutManager(Inf.context, 2));
        GridLayoutManager g1 = new GridLayoutManager(Inf.context, 2);
        LinearLayoutManager l1 = new LinearLayoutManager(Inf.context);
        recyclerView.setLayoutManager(l1);

        Switch mode = view.findViewById(R.id.rental_switch);
        mode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    recyclerView.setAdapter(borrowAdapter);

                    recyclerView.setLayoutManager(g1);
                } else {
                    recyclerView.setAdapter(lendAdapter);

                    recyclerView.setLayoutManager(l1);
                }
            }
        });
        SwipeRefreshLayout refreshLayout = view.findViewById(R.id.rental_refresh);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
                myHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                }, 1000);
            }
        });

        view.findViewById(R.id.rental_backbutton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isRefresh)Inf.instrumentFragment.refresh();
                changeFragment(Inf.centerFragment);
            }
        });
        refresh();
        return view;
    }

    public void refresh() {
        new RentalThread().start();
    }

    class RentalThread extends Thread {
        @Override
        public void run() {
            Rentals res = GetResult.QueryRentals(Inf.stuInf.StudentAccount, 0);
            if (res != null) {
                borrowAdapter.borrows = res.rentals;
                myHandler.sendEmptyMessage(0);
            }
            res = GetResult.QueryRentals(Inf.stuInf.StudentAccount, 1);
            if (res != null) {
                lendAdapter.lends = res.rentals;
                myHandler.sendEmptyMessage(1);
            }
        }
    }
}
